<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="账号">
              <a-input
                :style="{ width: '200px' }"
                allow-clear
                v-model="pageData.dropDownData"
                class="bacClass"
                placeholder=""
                @press-enter="huiche"
              ></a-input>
            </a-form-item>
            <a-form-item label="员工名称">
              <a-input
                :style="{ width: '200px' }"
                allow-clear
                v-model="pageData.nickName"
                class="bacClass"
                placeholder=""
                @press-enter="huiche"
              ></a-input>
            </a-form-item>
          </a-form>
        </div>

        <div class="my-tool-bar">
          <Toolbar
            :items="pageData.btnList"
            @select="selecth"
            @add="addHandler"
            @del="deleteHandler"
            @ResetPwd="ResetPwd"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                              <a-tab-pane title="用户列表"> -->

      <encapsulation-agrid
        style="height: 100%"
        ref="gridOption"
        :configaggrid="configTable1"
      ></encapsulation-agrid>
      <!-- <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        v-loading="pageData.pageLoading"
      ></AgGridVuesCopys> -->
      <!-- </a-tab-pane>
                          </a-tabs> -->
    </template>
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="cancel"
      :ok-loading="saveLoading"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="100px"
            label="账号"
            field="username"
            :rules="[{ required: true, message: '请输入账号' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.username" />
          </a-form-item>
          <a-form-item
            label-col-flex="100px"
            label="员工名称"
            field="nickName"
            :rules="{ required: true, message: '请输入昵称' }"
            :validate-trigger="['change', 'blur']"
          >
            <a-input placeholder="" v-model="dataForm.nickName" class="bacClass" />
          </a-form-item>
          <a-form-item
            label-col-flex="100px"
            label="是否本集团"
            field="judgeGroup"
            :rules="[{ validator: isChiese }, { required: true, message: '请选择' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              allow-clear
              v-model="dataForm.judgeGroup"
              class="bacClass"
            >
              <a-option :value="0">本集团</a-option>
              <a-option :value="1">外加工</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="选择角色"
            label-col-flex="100px"
            @click="getData"
            field="roleIdAndName"
            :rules="[{ required: true, message: '请选择' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              v-model="dataForm.roleIdAndName"
              @change="roleChange"
              multiple
              :disabled="pageData.sideTitle == '修改用户资料'"
            >
              <a-option
                v-for="option in options1"
                :value="option.id + '&' + option.roleName"
                :key="option.id"
                >{{ option.roleName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="公司" field="firmGroupId">
            <a-cascader
              v-model="dataForm.firmGroupId"
              :options="pageData.firmGroupList"
              allow-clear
              ref="casOb"
              class="bacClass"
              :title="pageData.title"
              :loading="pageData.loading"
              disabled
              popup-container="html"
            />
          </a-form-item>
          <a-form-item label-col-flex="100px" label="部门" field="departmentId">
            <a-cascader
              v-model="dataForm.department"
              :options="pageData.bmList"
              allow-clear
              ref="casOb1"
              disabled
              class="bacClass"
              :title="pageData.title1"
              :loading="pageData.loading1"
              popup-container="html"
            />
            <!-- <a-input class="bacClass" placeholder="" v-model="dataForm.department" disabled /> -->
          </a-form-item>
          <!-- :disabled="dataForm.firmGroupId == '' || dataForm.firmGroupId == null" -->
          <!-- :class="{ bacClass: !(dataForm.firmGroupId == null || dataForm.firmGroupId == '') }" -->
          <a-form-item label-col-flex="100px" label="关联员工" field="employeeId">
            <a-select
              popup-container="html"
              allow-search
              allow-clear
              v-model="dataForm.employeeId"
              class="bacClass"
              @change="employeeChange"
              @search="getEmployees"
            >
              <a-option v-for="(item, index) in ygselectlist" :value="item.id"
                >{{ item.code }}---{{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <!-- <paginationCopys
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :page-size-options="pagingList1"
    /> -->
    <!-- <a-modal
                :visible="pageData.changePwd"
                title="修改密码"
                @ok="changePasswordHandler"
                @cancel="pageData.changePwd = false"
        >
            <a-form :model="pwdData">
                <a-form-item label="密码">
                    <a-input class="bacClass" type="password" v-model="pwdData.pwd" placeholder=""></a-input>
                </a-form-item>
                <a-form-item label="确认密码">
                    <a-input
                            class="bacClass"
                            type="password"
                            v-model="pwdData.confirmPwd"
                            placeholder=""
                    ></a-input>
                </a-form-item>
            </a-form>
        </a-modal> -->
    <a-modal
      :visible="roleData.show"
      title="设置角色"
      @ok="roleOk()"
      @cancel="roleData.show = false"
    >
      <a-form :model="pwdData">
        <a-form-item label="选择角色">
          <a-select popup-container="html" class="bacClass" v-model="roleData.roleid" multiple>
            <a-option v-for="item in roleData.roleOptions" :value="item.id" :key="item.id"
              >{{ item.roleName }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      :visible="pageData.firmShow"
      title="设置公司权限"
      @ok="firmOk"
      @cancel="pageData.firmShow = false"
      width="800px"
    >
      <div style="height: 100%; display: flex; justify-content: space-between">
        <a-card title="公司" hoverable style="width: 49%; height: 100%">
          <a-scrollbar style="width: 100%; height: 100%; overflow: auto">
            <a-tree
              ref="tree"
              :checkable="true"
              v-model:checked-keys="pageData.firmId"
              :data="pageData.firmOptions"
              default-expand-all
              checked-strategy="all"
              @check="firmSelect"
              style="width: 100%; height: 500px; overflow: auto"
            />
          </a-scrollbar>
        </a-card>

        <a-card title="部门" hoverable style="width: 49%; height: 100%">
          <a-scrollbar style="width: 100%; height: 100%; overflow: auto">
            <a-tree
              :checkable="true"
              v-model:checked-keys="pageData.addDepIdList"
              :data="pageData.depOptions"
              default-expand-all
              style="width: 100%; height: 500px; overflow: auto"
            />
          </a-scrollbar>
        </a-card>
      </div>
    </a-modal>
    <a-modal
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="打印"
      cancelText="关闭"
      unmountOnClose
    >
      <template #title> 打印二维码</template>
      <div id="userlist">
        <QrcodeVue :value="qrData.code"></QrcodeVue>
        <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
          <span>公司: {{ decodeURI(qrData.firmName) }}</span>
          <br />
          <span>部门: {{ decodeURI(qrData.department) }}</span>
          <br />
          <!-- <span>组别: {{ decodeURI(qrData.zu) }}</span>
                              <br /> -->
          <span>账号: {{ decodeURI(qrData.username) }}</span>
          <br />
          <span>工号: {{ decodeURI(qrData.staffCode) }}</span>
          <br />
        </div>
      </div>
    </a-modal>
    <a-modal
      :width="800"
      v-model:visible="visibleYl"
      :on-before-ok="handleOks"
      @cancel="handleCancels"
      :mask-closable="false"
    >
      <template #title> 设置机台</template>
      <a-spin :loading="searchData.cgsLoading" tip="加载中" dot style="width: 100%; z-index: 999">
        <div class="jtButton">
          <a-form ref="formRef" layout="inline" :model="searchData" size="mini">
            <CorporateSectorCascader
              ref="corPor"
              :configCascader="configCascader"
              @changeCascader="changeCascader"
            />
            <a-form-item label="楼层">
              <a-input
                class="bacClass"
                v-model="searchData.sloteTolbal"
                :style="{ width: '15rem' }"
                allow-clear
              />
            </a-form-item>
          </a-form>

          <a-button type="primary" size="mini" @click="cxCgsLists">查询</a-button>
        </div>
        <a-tabs :lazy-load="true" :justify="true" :default-active-key="1" @change="userTypeChanges">
          <a-tab-pane :key="1" title="织厂">
            <a-table
              :style="{
                height: '500px',
                marginTop: '10px',
              }"
              :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
              rowKey="id"
              v-model:selected-keys="selectedRowKeys2"
              stripe
              :bordered="true"
              :scrollbar="true"
              sticky-header
              :pagination="false"
              :columns="cgColumns"
              :data="wlListXqs"
            >
            </a-table>
          </a-tab-pane>
          <a-tab-pane :key="2" title="染厂">
            <a-table
              :style="{
                height: '500px',
                marginTop: '10px',
              }"
              :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
              rowKey="id"
              v-model:selected-keys="selectedRowKeys3"
              stripe
              :bordered="true"
              :scrollbar="true"
              sticky-header
              :pagination="false"
              :columns="cgColumns"
              :data="wlListXqs2"
            >
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-modal>
    <a-modal
      title-align="start"
      mask="false"
      :hide-cancel="true"
      ok-text="关闭"
      :maskClosable="false"
      v-model:visible="visiblePwd"
      @ok="handlePwdOk"
      @cancel="handlePwdCancel"
    >
      <template #title>
        {{ pwdTitle }}
      </template>
      <div style="text-align: center">
        <span style="margin-right: 20px"
          >账号:{{ pwdTitle === '重置账号密码详情' ? pwdData.username : dataForm.username }}</span
        >
        <span>密码:{{ pwdTitle === '重置账号密码详情' ? pwdData.pwd : plaintext }}</span>
      </div>
    </a-modal>
    <a-modal
      :visible="pageData.changePwd"
      title="重置密码"
      @ok="changePasswordHandler"
      @cancel="pageData.changePwd = false"
    >
      <a-form :model="pwdData">
        <a-form-item label="账号">
          <a-input class="bacClass" v-model="pwdData.username" placeholder=""></a-input>
        </a-form-item>
        <a-form-item label="密码">
          <a-input class="bacClass" type="password" v-model="pwdData.pwd" placeholder=""></a-input>
        </a-form-item>
        <a-form-item label="确认密码">
          <a-input
            class="bacClass"
            type="password"
            v-model="pwdData.confirmPwd"
            placeholder=""
          ></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get, put } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import md5 from 'js-md5'
  import { ref, reactive, onMounted, toRefs,getCurrentInstance } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import axios from 'axios'
  import { baseURL } from '@/api/axios.config'
  import XqService from './service/xq/index'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  
  import { AnyARecord } from 'dns'
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import usePermission from '@/store/modules/permission'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import { values } from 'lodash'
  import CryptoJS from 'crypto-js'
  import emitter from '@/hooks/useEventBus'

  import { slicing } from '@/utils/caseFrimAndSecRig'
  import { sassFalse } from 'sass'
import { refAutoReset } from '@vueuse/core'
const instance: any = getCurrentInstance()

  interface Firm {
    name: string
    id: number
  }

  interface User {
    employeeId: any
    id: number | string
    firmGroupId: any
    username: string
    nickName: string
    deleteState: number | string
    gmtCreate: string
    gmtModified: string
    department: any
    zu: any
    firmName: any
    staffCode: any
    roleId: any
    judgeGroup: any
    departmentId: any
    companyIdList: any
    roleList: any
  }

  export default {
    name: 'UserList',
    setup: function () {
      const options1: any = ref([])
      const gridOption = ref()

      function getData() {
        get({
          url: '/admin/acl/role/selectRole',
        }).then(({ data, code }: any) => {
          if (code === 200) {
            options1.value = data.list
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      let depsData: any
      let parentNode=ref<any>([])
      const firmSelect = (selectedKeys: any, data: any) => {
        console.log(selectedKeys);
        console.log(data);
        //筛选父节点
        let parentArr:any=[]
        data.halfCheckedNodes.forEach((item:any)=>{
          let obj:any={
            type:0,
            firId:item.value,
            selectState:1
          }
          parentArr.push(obj)
        })
        parentNode.value=parentArr
        console.log(parentNode.value);
        
        
        depsData = []
        post({
          url: 'org/baCompany/getDepartmentTree?companyId=' + data.node.value,
        }).then((result) => {
          if (result.code === 200) {
            depsData = result.data
            pageData.depOptions = suitableFields(depsData)
          } else {
            Message.error(result.message)
          }
        })
      }

      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }

      const pageData = reactive<{
        gcList: Firm[]
        firmGroupList: []
        showAdd: boolean
        sideTitle: string
        changePwd: boolean
        options: any[]
        nameList: any[]
        dropDownData: any
        frimList: any[]
        department: any
        firmTypeId: any
        bmList: any[]
        zuList: any[]
        firmName: any
        pageLoading: boolean
        firmOptions: any[]
        depOptions: any[]
        firmId: any[]
        addDepIdList: any[]
        firmDefaultIdList: any[]
        depDefaultIdList: any[]
        firmShow: boolean
        rowlist: any[]
        defaultState: any[]
        isShow: boolean
        title: any
        title1: any
        judgeGroup: any
        loading: boolean
        loading1: boolean
        btnList: any[]
        nickName: any
      }>({
        gcList: [],
        firmGroupList: [],
        changePwd: false,
        showAdd: false,
        sideTitle: '新增登录账号',
        options: [],
        nameList: [],
        dropDownData: '',
        frimList: [],
        firmDefaultIdList: [],
        depDefaultIdList: [],
        department: '',
        firmTypeId: '',
        bmList: [],
        zuList: [],
        firmName: '',
        pageLoading: false,
        firmOptions: [],
        depOptions: [],
        firmId: [],
        addDepIdList: [],
        firmShow: false,
        rowlist: [],
        defaultState: [],
        isShow: true,
        title: '',
        judgeGroup: '',
        title1: '',
        loading: false,
        loading1: false,
        btnList: [],
        nickName: '', //员工名称
      })
      let cxbl = ''
      const selecth = () => {
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const headerShow = ref<boolean>(true)

      function doRefresh() {
        if (pageData.pageLoading) return
        pageData.pageLoading = true
        // get({
        //   url: '/admin/acl/user/findUserFirmGroup',
        //   data: {
        //     page: pagination.page,
        //     limit: pagination.pageSize,
        //     username: pageData.dropDownData,
        //   },
        // })
        //   .then(({ data, code }: any) => {
        //     if (code === 200) {
        //       for (var i = 0; i < data.items.length; i++) {
        //         var ob = data.items[i]
        //         if (
        //           ob.firmTypeName != null &&
        //           ob.firmTypeName != undefined &&
        //           ob.firmTypeName != ''
        //         ) {
        //           ob.firmName = ob.firmTypeName + '-' + ob.firmName
        //         }
        //       }
        //       console.log(gridOption);

        //       gridOption.value.setdataListIterface(data.items)
        //       table.handleSuccess(data.items)
        //       pagination.setTotalSize(data.page.total)
        //     }
        //   })
        //   .finally(() => {
        //     pageData.pageLoading = false
        //   })
        try {
          gridOption.value.setQuery({
            username: pageData.dropDownData,
            nickName: pageData.nickName,
          })
        } catch (error) {
          console.log(error)
        } finally {
          pageData.pageLoading = false
        }
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //下拉框得到焦点
      const focusSel = () => {
        selCxAll('')
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          loading.value = true
          selCxAll(value)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        get({
          url: 'admin/acl/user/index?page=1&limit=30&username=' + val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.nameList = data.items
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'firmName',
          dataIndex: 'firmName',
          width: 150,
        },
        {
          title: '部门',
          key: 'department',
          dataIndex: 'department',
          width: 150,
        },
        // {
        //     title: "组",
        //     key: "zu",
        //     dataIndex: "zu",
        //     width: 150,
        // },
        {
          title: '账号',
          key: 'username',
          dataIndex: 'username',
          width: 150,
        },
        {
          title: '员工名称',
          key: 'nickName',
          dataIndex: 'nickName',
          width: 150,
        },
        {
          title: '工号',
          key: 'staffCode',
          dataIndex: 'staffCode',
          width: 150,
        },
        {
          title: '角色',
          key: 'roleName',
          dataIndex: 'roleName',
          width: 150,
        },
        {
          title: '是否为本集团',
          key: 'judgeGroup',
          dataIndex: 'judgeGroup',
          slotName: 'judgeGroup',
          width: 150,
          fixed: 'right',
        },
        {
          title: '操作',
          key: 'id',
          slotName: 'action',
          width: 400,
          fixed: 'right',
        },
      ])
      const data1 = ref<any[]>([])

      onMounted(async () => {
        emitter.on("refresh-UserList", () => doRefresh());
        await getData()
      })
      const queryData = reactive({
        firm: '',
        clothType: '',
      })
      const addHandler = () => {
        getFirmGroup()
        getEmployees('')
        for (var key in dataForm) {
          dataForm[key] = ''
        }
        pageData.showAdd = true

        pageData.sideTitle = '新增登录账号'
      }
      const dataForm: any = reactive({
        id: '',
        firmGroupId: '',
        firmState: '',
        employeeId: 0,
        nickName: '',
        username: '',
        deleteState: 0,
        gmtCreate: '',
        gmtModified: '',
        department: '',
        zu: '',
        firmName: '',
        staffCode: '',
        roleId: '',
        judgeGroup: '',
        departmentId: null,
        companyIdList: '',
        roleList: [],
        roleIdAndName: '',
      })
      const plaintext = ref('')
      const newAddUsername = ref('')
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        saveLoading.value = true
        // console.log(dataForm.roleIdAndName.map((res: any) => parseInt(res.split('&')[0], 10)))
        formRef.value?.validate().then(async (err) => {
          if (!err) {
            if (dataForm.firmGroupId == '') {
              dataForm.firmGroupId = 0
            }
            if (dataForm.companyIdList == '' || dataForm.companyIdList == null) {
              dataForm.companyIdList = []
            }
            if (
              dataForm['employeeId'] != undefined &&
              dataForm['employeeId'] != null &&
              dataForm['employeeId'] != ''
            ) {
              var ob = ygselectlist.value.filter(function (o) {
                return dataForm.employeeId == o.id
              })[0]
              dataForm.staffCode = ob['code']
            }
            dataForm['firmGroupId'] =
              dataForm['firmGroupId'] == null ||
              dataForm['firmGroupId'] == '' ||
              dataForm['firmGroupId'] == undefined
                ? 0
                : dataForm['firmGroupId']
            dataForm['employeeId'] =
              dataForm['employeeId'] == null ||
              dataForm['employeeId'] == '' ||
              dataForm['employeeId'] == undefined
                ? 0
                : dataForm['employeeId']
            dataForm['departmentId'] =
              dataForm['departmentId'] == null ||
              dataForm['departmentId'] == '' ||
              dataForm['departmentId'] == undefined
                ? 0
                : dataForm['departmentId']
            if (dataForm.judgeGroup == 0) {
              if (
                dataForm.employeeId == 0 ||
                dataForm.firmGroupId == '' ||
                dataForm.departmentId == ''
              ) {
                Message.error({
                  content: '请填写公司/部门/关联员工的相关数据！',
                  duration: 5000,
                })
                return
              }
            }
            if (pageData.sideTitle === '新增登录账号') {
              try {
                const res = await get({
                  url: 'admin/acl/user/getRandomPws',
                })
                if (res.code == 200) {
                  saveLoading.value = true
                  // 密文
                  let formatsecret = res.data.data
                  const arr = []
                  for (let i = 0; i < formatsecret.length; i++) {
                    arr.push(formatsecret[i])
                  }
                  // console.log('arr',arr)
                  arr.splice(15, 1)
                  arr.splice(9, 1)
                  arr.splice(7, 1)
                  arr.splice(3, 1)
                  const ciphertext = arr.join('').toString()
                  console.log('ciphertext', ciphertext)
                  // 密钥和偏移量
                  const key = 'YourSecretKey123'
                  const iv = 'YourSecretKey123'
                  // 将密文转换为 WordArray 对象
                  const ciphertextBytes = CryptoJS.enc.Base64.parse(ciphertext)
                  const ciphertextWordArray = CryptoJS.lib.CipherParams.create({
                    ciphertext: ciphertextBytes,
                  })
                  // 解密
                  const plaintextWordArray = CryptoJS.AES.decrypt(
                    ciphertextWordArray,
                    CryptoJS.enc.Utf8.parse(key),
                    {
                      mode: CryptoJS.mode.ECB,
                      padding: CryptoJS.pad.Pkcs7,
                    }
                  )
                  // 将解密后的 WordArray 对象转换为字符串
                  plaintext.value = plaintextWordArray.toString(CryptoJS.enc.Utf8)
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              } catch (error) {
                console.log(error)
              }

              dataForm.deleteState = 'false'
              let pwd = md5(plaintext.value)
              //3,8,20,27
              const pwdarr = pwd.split('')
              pwdarr.splice(3, 0, 'a')
              pwdarr.splice(8, 0, 'b')
              pwdarr.splice(20, 0, 'a')
              pwdarr.splice(27, 0, 'b')
              pwd = pwdarr.join('')
              dataForm['password'] = pwd
              dataForm['companyIdList'] = [dataForm.firmGroupId]
              try {
                const res = await post({
                  url: `org/baCompany/getEmpIdCompany?id=${dataForm.employeeId}`,
                })
                if (res.code == 200) {
                  dataForm['firmName'] = res.data.companyName
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              } catch (error) {
                console.log(error)
              }
              try {
                const res = await post({
                  url: 'admin/acl/user/save',
                  data: {
                    ...dataForm,
                    roleId: dataForm.roleIdAndName.map((res: any) => res.split('&')[0]),
                    roleName: dataForm.roleIdAndName.map((res: any) => res.split('&')[1]),
                  },
                })
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  pwdTitle.value = '新增用户详情'
                  //开启密码弹窗 显示密码
                  visiblePwd.value = true
                  newAddUsername.value = res.username
                  // Message.success({
                  //     content: '新增成功',
                  //     duration: 5000,
                  // })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              } catch (error) {
                console.log(error)
              } finally {
                saveLoading.value = false
              }
            } else {
              dataForm['password'] = undefined
              if (dataForm.employeeId == 0) {
                dataForm.staffCode = ''
              }
              dataForm.roleId = dataForm.roleIdAndName.map((res: any) => Number(res.split('&')[0]))
              dataForm.roleName = dataForm.roleIdAndName.map((res: any) => res.split('&')[1])
              try {
                const res = await put({
                  url: '/admin/acl/user/update',
                  data: {
                    ...dataForm,
                    roleId: dataForm.roleIdAndName.map((res: any) => res.split('&')[0]),
                    roleName: dataForm.roleIdAndName.map((res: any) => res.split('&')[1]),
                  },
                })
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              } catch (error) {
                console.log(error)
              } finally {
                saveLoading.value = false
              }
            }
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              // url: 'admin/acl/user/batchRemove?idList=' + selectedRowKeys.value.join(','),
              url:
                'admin/acl/user/batchRemove?idList=' +
                gridOption.value
                  .getSelectedRows()
                  .map((o: any) => {
                    return o.id
                  })
                  .join(','),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const cancel = () => {
        formRef.value?.resetFields()

        dataForm.nickName = ''
        dataForm.username = ''

        pageData.showAdd = false
      }
      const editHandler = (record: User) => {
        for (let key in record) {
          dataForm[key] = record[key]
        }
        dataForm['companyIdList'] = [record.firmGroupId]
        getFirmGroup()
        console.log('record', record)
        post({
          url: `org/baCompany/getEmpIdCompany?id=${record.employeeId}`,
        }).then((result) => {
          if (result.code == 200) {
            dataForm.firmGroupId = result.data.companyId
            dataForm.firmName = result.data.companyName
            dataForm.departmentId = result.data.departmentId
            dataForm.department = result.data.depName
          } else {
            Message.error({
              content: result.message,
              duration: 5000,
            })
          }
        })

        if (dataForm.firmGroupId != 0) {
          dataForm.firmGroupId = record.firmGroupId
        } else {
          dataForm.firmGroupId = null
        }
        if (dataForm.employeeId == undefined && dataForm.employeeId == 0) {
          dataForm.employeeId = null
        } else {
          // ygselectById(dataForm.employeeId)
        }
        // dataForm.roleId = dataForm.roleIdAndName.map((res:any)=> Number(res.split('&')[0]))
        // dataForm.roleName = dataForm.roleIdAndName.map((res:any)=> res.split('&')[1])
        // dataForm.roleIdAndName = dataForm.roleId
        dataForm.roleIdAndName = []
        if (dataForm.roleId != null && dataForm.roleId.length != 0) {
          nextTick(() => {
            dataForm.roleId.forEach((res: any, index: any) => {
              dataForm.roleIdAndName[index] = res + '&' + dataForm.roleName[index]
            })
          }).finally(() => {
            pageData.pageLoading = false
          })
        }
        pageData.sideTitle = '修改用户资料'
        pageData.showAdd = true
        getEmployees(record.staffCode)
        // getAllFirmData(record, 1)
        // if (record.firmGroupId != 0) {
        //   getBmGroup(record.firmGroupId)
        // }
        // if (dataForm.departmentId != 0) {
        //   ygselect(dataForm.departmentId)
        // }
        dataForm['firmGroupId'] = dataForm['firmGroupId'] == 0 ? null : dataForm['firmGroupId']
        dataForm['employeeId'] = dataForm['employeeId'] == 0 ? null : dataForm['employeeId']
        dataForm['departmentId'] = dataForm['departmentId'] == 0 ? null : dataForm['departmentId']
      }
      const pwdData = reactive({
        username: '',
        curId: '',
        pwd: '',
        confirmPwd: '',
      })
      const changePwd = (record: any) => {
        pwdData.username = record.username
        pwdData.curId = record.id
        pwdData.confirmPwd = ''
        pwdData.pwd = ''
        pageData.changePwd = true
      }
      const changePasswordHandler = async () => {
        if (pwdData.pwd !== pwdData.confirmPwd) {
          Message.error({
            content: '两次输入密码不一样！',
            duration: 5000,
          })
          return
        }
        let pwd = md5(pwdData.pwd)
        //3,8,20,27
        const pwdarr = pwd.split('')
        pwdarr.splice(3, 0, 'a')
        pwdarr.splice(8, 0, 'b')
        pwdarr.splice(20, 0, 'a')
        pwdarr.splice(27, 0, 'b')
        pwd = pwdarr.join('')
        let result = await post({
          url: 'admin/acl/user/updateUserPassWord',
          data: {
            id: pwdData.curId,
            password: pwd,
          },
        })

        if (result.code === 200) {
          pageData.changePwd = false
          //弹出提示框
          pwdTitle.value = '重置账号密码详情'
          visiblePwd.value = true
          Message.success({
            content: '修改密码成功',
            duration: 5000,
          })
          return true
        } else {
          Message.error({
            content: '修改失败',
            duration: 5000,
          })
          pageData.changePwd = false
          return false
        }
      }
      const roleData = reactive<{
        userId: string | number
        roleid: string | number
        roleOptions: any[]
        show: boolean
      }>({
        userId: '',
        roleid: '',
        roleOptions: [],
        show: false,
      })
      const setRole = (record: User) => {
        roleData.roleid = ''
        get({
          url: 'admin/acl/user/toAssign',
          data: {
            userId: record.id,
          },
        }).then(({ code, data }) => {
          if (code === 200) {
            try {
              roleData.roleOptions = data.allRolesList
              roleData.userId = record.id
              if (Array.isArray(data.assignRoles) && data.assignRoles.length > 0) {
                let idStr: any = []
                data.assignRoles.forEach(function (o: any) {
                  idStr.push(o['id'])
                })
                roleData.roleid = idStr
              }
              roleData.show = true
            } catch (e) {
              Message.error('获取角色信息失败')
            }
          } else {
            Message.error('获取角色信息失败')
          }
        })
      }

      const roleOk = () => {
        post({
          url: `admin/acl/user/doAssign?userId=${roleData.userId}&roleId=${roleData.roleid}`,
        }).then(({ code, data }) => {
          if (code === 200) {
            roleData.show = false
            doRefresh()
            Message.success('修改角色成功')
          } else {
            Message.error('修改角色失败')
          }
        })
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      // 获取公司列表
      const getFirmGroup = () => {
        post({
          url: 'org/baCompany/getTreeCompanyOrDepartment',
          data: {},
        }).then(({ code, data }) => {
          if (code === 200) {
            pageData.firmGroupList = data
          }
        })
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      //生成条码
      let qrData: any = reactive({
        firmName: '',
        department: '',
        zu: '',
        username: '',
        staffCode: '',
        nickName: '',
      })
      const visible = ref(false)

      const handleOk = () => {
        printJS({
          printable: 'userlist',
          type: 'html',
          targetStyles: ['*'],
        })
        visible.value = false
      }
      const handleCancel = () => {
        visible.value = false
      }

      const GenerateBtn = (record: any) => {
        visible.value = true
        qrData.firmName = record.firmName
        qrData.department = record.department
        // qrData.zu = record.zu
        qrData.username = record.username
        qrData.staffCode = record.staffCode
        qrData.nickName = record.nickName
        qrData.staffCode = record.staffCode
        qrData.code = JSON.stringify({
          // firmName: encodeURI(record.firmName),
          // department: encodeURI(record.department),
          // zu: encodeURI(record.zu),
          username: encodeURI(record.username),
          staffCode: encodeURI(record.staffCode),
          nickName: encodeURI(record.nickName),
        })
      }
      const ygselectlist = ref<any[]>([])

      async function ygselect(v: string) {
        pageData.loading = true
        pageData.loading1 = true
        post({
          url: 'org/hrEmployee/getList',
          data: {
            deleteState: 0,
            obsoleteState: 0,
            company_id: dataForm.firmGroupId,
            department_id: v,
          },
        })
          .then(({ data, code }) => {
            if (code === 200) {
              ygselectlist.value = data
            }
          })
          .finally(() => {
            pageData.loading = false
            pageData.loading1 = false
          })
      }

      let userId: any = null
      let testData: any

      //拿到所有公司（新）
      function getAllFirmData(record: any, num: any) {
        pageData.firmOptions = []
        pageData.depOptions = []
        pageData.firmId = []
        pageData.firmDefaultIdList = []
        pageData.depDefaultIdList = []
        pageData.addDepIdList = []
        userId = record.id + ''
      
        if (num != 1) {
          // 查询:回显此用户公司权限
          get({
            url: 'admin/acl/user/findUserId?id=' + userId,
          }).then(({ data, code }) => {
            if (code === 200) {
              if (data.data.length > 0) {
                data.data.forEach(function (o: any) {
                  if (o.firmState == 0) {
                    if (o['defaultState'] == 0) {
                      pageData.firmDefaultIdList.push(o['firmGroupId'])
                    }
                    if (o['selectState'] == 1) {
                      pageData.firmId.push(o['firmState'] + '-' + o['firmGroupId'])
                    }
                  } else if (o.firmState == 1) {
                    if (o['defaultState'] == 0) {
                      pageData.depDefaultIdList.push(o['firmGroupId'])
                    }
                    if (o['selectState'] == 1) {
                      pageData.addDepIdList.push(o['firmState'] + '-' + o['firmGroupId'])
                    }
                  }
                })
                console.log(pageData.firmId)
                console.log(pageData.firmDefaultIdList)
              }
              // 查询所有公司
              post({
                url: 'org/baCompany/getTreeCompanyOrDepartment',
                data: {},
              }).then((result) => {
                if (result.code === 200) {
                  testData = result.data
                  pageData.firmOptions = suitableFields(result.data)
                  if (num != 1) {
                    pageData.firmShow = true
                  }
                } else {
                  Message.error(result.message)
                }
              })
            } else {
              Message.error('保存公司权限失败')
            }
          })
        }
      }

      //递归将字段改成树的渲染
      function suitableFields(temp: any) {
        temp.forEach(function (o: any) {
          o['title'] = o.label
          o['key'] = o.type + '-' + o.value
          o['name'] = o.name
          o['type'] = o.type
          if (o.type == 0) {
            if (pageData.firmDefaultIdList.includes(o.value)) {
              o['disableCheckbox'] = true
            }
          } else if (o.type == 1) {
            if (pageData.depDefaultIdList.includes(o.value)) {
              o['disableCheckbox'] = true
            }
          }
          if (o.children != undefined && o.children.length != 0) {
            suitableFields(o['children'])
          }
        })
        return temp
      }

      interface TreeNode {
        key: string
        name: string
        children?: TreeNode[]
      }

      //处理树形组织架构参数的函数
      // const findSelectedNodeData = (
      //     targetId: any,
      //     array: TreeNode[],
      //     parentData: TreeNode | null = null,
      //     result: TreeNode[] = []
      // ): TreeNode[] => {
      //     for (const item of array) {
      //         if (item.key === targetId) {
      //             if (parentData) {
      //                 result.unshift(parentData)
      //             }
      //             result.push(item)
      //             return result
      //         }
      //         if (item.children && item.children.length > 0) {
      //             const newPath = parentData ? [...result, parentData, item] : [...result, item]
      //             const foundNodes = findSelectedNodeData(targetId, item.children, item, newPath)
      //             if (foundNodes.length > 0) {
      //                 return foundNodes
      //             }
      //         }
      //     }
      //     return []
      // }
      //设置公司保存
      const firmOk = () => {
        var firmList = pageData.firmId.map((z: any) => {
          return {
            type: Number(z.split('-')[0]),
            firId: Number(z.split('-')[1]),
            selectState: 1,
          }
        })
        var depsList = pageData.addDepIdList.map((z: any) => {
          return {
            type: Number(z.split('-')[0]),
            firId: Number(z.split('-')[1]),
            selectState: 1,
          }
        })
        const mergedArray = firmList.concat(depsList)
        post({
          url: 'admin/acl/user/saveUserFirmGroupBatch?userId=' + userId,
          data:[...mergedArray,...parentNode.value],
        }).then(({ data, code }) => {
          if (code === 200) {
            pageData.firmShow = false
            Message.success('保存成功！')
            pageData.firmDefaultIdList = []
            doRefresh()
          } else {
            Message.error('保存公司权限失败')
          }
        })
      }

      // const gridReady = (params: any) => {
      //   gridOption.value = params.api
      // }

      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = '550px'
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <a-tag class="tagCss" @click="a" v-if="f">

                修 改
              </a-tag>

              <a-tag @click="c" class="tagCss" v-if="h">

                设置角色
              </a-tag>
              <a-tag @click="d" class="tagCss" v-if="i">
                设置公司权限
              </a-tag>
              <a-tag @click="k" class="tagCss">
                设置机台权限
              </a-tag>
              <a-tag @click="e" class="tagCss" v-if="j">
                二维码
              </a-tag>
            </a-space>`,
            setup(props: any) {
              const a = () => {
                getData()
                editHandler(props.params.data)
              }
              const b = () => {
                changePwd(props.params.data)
              }
              const c = () => {
                setRole(props.params.data)
              }
              const d = () => {
                getAllFirmData(props.params.data, 2)
              }
              const e = () => {
                GenerateBtn(props.params.data)
              }
              const k = () => {
                SettingMachine(props.params.data)
              }
              let f = permissionStore.hasPermisson('yhlb.xg')
              let g = permissionStore.hasPermisson('yhlb.ghmm')
              let h = permissionStore.hasPermisson('yhlb.szjs')
              let i = permissionStore.hasPermisson('yhlb.szjsqx')
              let j = permissionStore.hasPermisson('yhlb.ewm')
              return {
                a,
                b,
                c,
                d,
                e,
                f,
                g,
                h,
                i,
                j,
                k,
              }
            },
          }
        }
        if (o.slotName === 'judgeGroup') {
          obj['resizable'] = false
          obj['filter'] = true
          obj['filterParams'] = {
            valueFormatter: function (params: any) {
              return params.value == '0' ? '本集团' : params.value == '1' ? '外加工' : ''
            },
          }
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = '120px'
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <el-tag type="success" @click="a" v-if="a==0">
                {{ val }}
              </el-tag>
              <el-tag type="warning" @click="b" v-if="a==1">
                {{ val }}
              </el-tag>
            </a-space>`,
            setup(props: any) {
              const val = ref()
              val.value = props.params.data.judgeGroup == 0 ? '本集团' : '外加工'
              return {
                val,
                a: props.params.data.judgeGroup,
              }
            },
          }
        }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let configTable1 = ref({
        url: 'admin/acl/user/findUserFirmGroup', //接口路径
        queryData: {
          //接口参数
        },
        isGet: true, //是否是get请求
        isLimit: true, //后端分页接收limit而非size
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: false, //点击行是否多选
        column: tc,
        fileName: 'userList',
      })
      const casOb = ref()
      const casOb1 = ref()
      //公司改变
      const cascaderChange = (val: any) => {
        if (!val) {
          getEmployees('')
        }
        pageData.bmList = []
        dataForm.employeeId = null
        dataForm.departmentId = null
        dataForm.department = ''
        dataForm.staffCode = ''
        dataForm.firmName = ''
        ygselectlist.value = []
        const casobj = casOb.value.selectedPath
        //拿到选中的这个节点数组
        setTimeout(function () {
          if (casobj.length !== 0) {
            dataForm.companyIdList = []
            var tempCas = casobj[casobj.length - 1].split('-')
            dataForm.companyIdList.push(tempCas[tempCas.length - 1])
            //过滤掉最高级 集团 不然会全选
            dataForm.companyIdList = dataForm.companyIdList.filter((item) => item !== '66')
          }
          if (casobj.length == 0) {
            dataForm.companyIdList = []
          }
          if (casOb.value.selectViewValue.length != 0) {
            dataForm.firmName = slicing(casOb.value.selectViewValue[0]['label'])
          }
        }, 100)
        if (val == '' || val == undefined) {
          dataForm.employeeId = null
        } else {
          pageData.isShow = false
        }
        getBmGroup(val)
        // ygselect('')
      }

      //部门改变
      const cascaderChange1 = (val: any) => {
        console.log('val', val)

        dataForm.employeeId = null
        dataForm.staffCode = ''
        dataForm.department = ''
        ygselectlist.value = []
        //拿到选中的这个节点数组
        setTimeout(function () {
          if (casOb1.value.selectViewValue.length != 0) {
            dataForm.department = slicing(casOb1.value.selectViewValue[0]['label'])
          }
        }, 100)
        if (val != null && val != undefined && val != '' && val != 0) {
          ygselect(val)
        }
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      // 获取部门列表
      const getBmGroup = (val: any) => {
        post({
          url: 'org/baCompany/getDepartmentTree?companyId=' + val,
        }).then((result) => {
          if (result.code === 200) {
            pageData.bmList = result.data
          }
        })
      }
      const pagingList1: any = ref(pagingList)
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()
      if (permissionStore.hasPermisson('yhlb.czmm')) {
        pageData.btnList.push('重置密码')
      }
      if (permissionStore.hasPermisson('yhlb.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('yhlb.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('yhlb.sc')) {
        pageData.btnList.push('删除')
      }

      // if (permissionStore.hasPermisson('yhlb.dc')) {
      //     pageData.btnList.push("导出")
      // }
      // if (permissionStore.hasPermisson('yhlb.dr')) {
      //     pageData.btnList.push("导入")
      // }
      // if (permissionStore.hasPermisson('yhlb.mbxz')) {
      //     pageData.btnList.push("模板下载")
      // }

      const visibleYl: any = ref(false)

      const selectedRowKeys2: any = ref([])
      const selectedRowKeys3: any = ref([])

      const searchData: any = reactive({
        sloteTolbal: '',
        frimIdSelect: null,
        cgsLoading: false,
      })

      const wlListXqs: any = ref([])

      const wlListXqs2: any = ref([])

      let getRowData: any

      const SettingMachine = async (rowData: any) => {
        searchData.frimIdSelect = null
        getRowData = rowData
        visibleYl.value = true
        searchData.cgsLoading = true
        corPor.value.resetForm()
        wlListXqs.value = []
        wlListXqs2.value = []
        await selectJtDat()
        await selectJtDat2()
        const res: any = await post({
          url: 'planSingle/empBindMachine/getMachineIdListByUserId',
          data: {
            userId: rowData.id,
          },
        })
        if (res.code == 200) {
          selectedRowKeys2.value = res.data
          searchData.frimIdSelect = null
          searchData.sloteTolbal = ''
        } else {
          Message.error(res.message)
        }
        searchData.cgsLoading = false
        const res2: any = await post({
          url: 'aps/empBindMachine/getMachineIdListByUserId',
          data: {
            userId: rowData.id,
          },
        })
        if (res2.code == 200) {
          selectedRowKeys3.value = res2.data
          searchData.frimIdSelect = null
          searchData.sloteTolbal = ''
        } else {
          Message.error(res.message)
        }
      }

      const handleOks = async () => {
        const res = await post({
          url: 'planSingle/empBindMachine/addBind',
          data: {
            userInfo: getRowData,
            machineList: wlListXqs.value.filter((res: any) => {
              return selectedRowKeys2.value.includes(res.id)
            }),
          },
        })
        const res2 = await post({
          url: 'aps/empBindMachine/addBind',
          data: {
            userInfo: getRowData,
            machineList: wlListXqs2.value.filter((res: any) => {
              return selectedRowKeys3.value.includes(res.id)
            }),
          },
        })
      }

      const handleCancels = () => {
        corPor.value.resetForm()
        visibleYl.value = false
      }

      let totalList: any = []
      let totalList2: any = []
      const cxCgsLists = () => {
        searchData.cgsLoading = true
        if (userTypes.value == 1) {
          let filteredValue = totalList
          if (searchData.frimIdSelect && !searchData.sloteTolbal) {
            filteredValue = totalList.filter((o: any) => o.firmId == searchData.frimIdSelect)
          }
          if (!searchData.frimIdSelect && searchData.sloteTolbal) {
            filteredValue = totalList.filter((o: any) => o.coordinate == searchData.sloteTolbal)
          }
          if (searchData.sloteTolbal && searchData.frimIdSelect) {
            filteredValue = totalList.filter(
              (o: any) =>
                o.firmId == searchData.frimIdSelect && o.coordinate == searchData.sloteTolbal
            )
          }
          if (!searchData.sloteTolbal && !searchData.frimIdSelect) {
            filteredValue = totalList
          }
          wlListXqs.value = filteredValue
          searchData.cgsLoading = false
        } else if (userTypes.value == 2) {
          let filteredValue2 = totalList2
          if (searchData.frimIdSelect && !searchData.sloteTolbal) {
            filteredValue2 = totalList2.filter((o: any) => o.firmId == searchData.frimIdSelect)
          }
          if (!searchData.frimIdSelect && searchData.sloteTolbal) {
            filteredValue2 = totalList2.filter((o: any) => o.coordinate == searchData.sloteTolbal)
          }
          if (searchData.sloteTolbal && searchData.frimIdSelect) {
            filteredValue2 = totalList2.filter(
              (o: any) =>
                o.firmId == searchData.frimIdSelect && o.coordinate == searchData.sloteTolbal
            )
          }
          if (!searchData.sloteTolbal && !searchData.frimIdSelect) {
            filteredValue2 = totalList2
          }
          wlListXqs2.value = filteredValue2
          searchData.cgsLoading = false
        }
      }

      const cgColumns: any = [
        {
          dataIndex: 'firm',
          key: 'firm',
          title: '公司',
          width: 150,
        },
        {
          dataIndex: 'machineCode',
          key: 'machineCode',
          title: '机台编号',
          width: 150,
        },
        {
          dataIndex: 'machineName',
          key: 'machineName',
          title: '机台名称',
          width: 150,
        },
        {
          dataIndex: 'areaName',
          key: 'areaName',
          title: '楼层',
          width: 150,
        },
      ]

      const corPor: any = ref()
      const configCascader = ref<{}>({
        corporateWidth: '15rem', //公司宽度
        sectorWidth: '180px', //部门宽度
        corporateRquired: false, //公司是否必填
        sectorRquired: false, //部门是否必填
        size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
        corporateName: '公司', //公司label
        sectorName: '选择部门', //部门label
        cascaderShow: 'sector', //配置部门不显示
      })

      const changeCascader = (data: any) => {
        const { corporateId } = data
        searchData.frimIdSelect = corporateId
      }

      function selectJtDat() {
        post({
          url: 'planSingle/machine/getMachinePara',
          data: {
            firmId: searchData.frimIdSelect || null,
            coordinate: searchData.sloteTolbal,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            wlListXqs.value = res.data
            totalList = res.data
          }
        })
      }

      function selectJtDat2() {
        post({
          url: 'aps/dwMachine/getMachinePara',
          data: {
            firmId: searchData.frimIdSelect == '' ? null : searchData.frimIdSelect,
            coordinate: searchData.sloteTolbal,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            wlListXqs2.value = res.data
            totalList2 = res.data
          }
        })
      }

      const userTypes = ref(1)

      const userTypeChanges = (e: any) => {
        userTypes.value = e
        cxCgsLists()
      }
      //控制密码弹窗
      const visiblePwd = ref(false)
      const handlePwdOk = () => {
        console.log('ok')
      }
      const handlePwdCancel = () => {
        console.log('cancel')
      }
      //弹窗标题
      const pwdTitle = ref('')
      //重置密码相关
      const ResetPwd = () => {
        if (
          gridOption.value?.getSelectedRows().length !== 0 &&
          gridOption.value?.getSelectedRows().length == 1
        ) {
          const currentRow = gridOption.value?.getSelectedRows()[0]
          pwdData.username = currentRow.username
          pwdData.curId = currentRow.id
          pwdData.confirmPwd = ''
          pwdData.pwd = ''
          pageData.changePwd = true
        } else {
          Message.error({
            content: '请勾选单条数据！',
            duration: 5000,
          })
        }
      }
      const employeeChange = (e: any) => {
        dataForm.firmGroupId = ''
        dataForm.department = ''
        if (!e) {
          getEmployees('')
          return
        }
        post({
          url: `org/baCompany/getEmpIdCompany?id=${e}`,
        }).then(
          (result) => {
            if (result.code == 200) {
              dataForm.firmGroupId = result.data.companyId
              getBmGroup(dataForm.firmGroupId)
              dataForm.department = result.data.depName
              dataForm.departmentId = result.data.departmentId
              dataForm.companyIdList = [result.data.companyId]
              dataForm.firmName = result.data.companyName
            } else {
              Message.error(result.message)
            }
          },
          (error) => {
            console.log(error)
          }
        )
        const filterArr: any = ygselectlist.value.filter((item: any) => item.id === e)
        dataForm.username = filterArr[0].name
        dataForm.nickName = filterArr[0].name
      }
      const getEmployees = (e: any) => {
        post({
          url: 'org/hrEmployee/getDepInfo',
          data: {
            code: '',
            name: e,
          },
        }).then(
          (result) => {
            if (result.code === 200) {
              ygselectlist.value = result.data.data.map((item: any) => {
                return {
                  name: item.name,
                  id: item.id,
                  code: item.code,
                }
              })
            } else {
              Message.error(result.message)
            }
          },
          (error) => {
            console.log(error)
          }
        )
      }
      const roleChange = (e) => {
        console.log(e)
      }
      const saveLoading = ref(false)
      return {
        corPor,
        roleChange,
        employeeChange,
        getEmployees,
        visiblePwd,
        handlePwdOk,
        handlePwdCancel,
        pwdTitle,
        ResetPwd,
        plaintext,
        newAddUsername,
        options1,
        getData,
        wlListXqs2,
        selectedRowKeys3,
        userTypes,
        userTypeChanges,
        searchData,
        changeCascader,
        configCascader,
        cgColumns,
        wlListXqs,
        selectedRowKeys2,
        cxCgsLists,
        handleCancels,
        handleOks,
        visibleYl,
        SettingMachine,
        pagingList1,
        cascaderChange1,
        casOb,
        casOb1,
        huiche,
        localeText1,
        cascaderChange,
        defaultColDef,
        tc,
        data1,
        // roletree,
        // rowlist,
        // zk,
        firmOk,
        ygselectlist,
        ygselect,
        roleOk,
        roleData,
        setRole,
        selecth,
        changePasswordHandler,
        changePwd,
        pwdData,
        cancel,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        isChiese,
        headerShow,
        focusSel,
        loading,
        handleSearch,
        getFirmGroup,
        PageSize,
        change1,
        handleChange,
        GenerateBtn,
        qrData,
        visible,
        handleOk,
        handleCancel,
        // gridReady,
        firmSelect,
        saveLoading,
        configTable1,
        gridOption,
      }
    },
    components: { Toolbar, QrcodeVue, CorporateSectorCascader },
  }
</script>
<style scoped lang="less">
  .active {
    color: red;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.arco-table-th) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.arco-table-td) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  .jtButton {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  :deep(.arco-btn-status-normal) {
    margin-top: 35px;
  }
</style>
